import React, { useState } from 'react';
import { Table, Button, Tag, Switch, Input, Space, Popconfirm, message } from 'antd';
import { SearchOutlined, EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { mockProducts, productCategories, productStatuses } from '../../api/mockServeData/mockData';

const ProductTable = ({ onEdit, onCreate, onRefresh }) => {
  const [data] = useState(mockProducts);
  const [searchText, setSearchText] = useState('');
  const [selectedStatus, setSelectedStatus] = useState(null);
  const [selectedCategory, setSelectedCategory] = useState(null);

  const getCategoryName = (id) => {
    const category = productCategories.find(cat => cat.id === id);
    return category ? category.name : '未知分类';
  };

  const getStatusInfo = (id) => {
    const status = productStatuses.find(s => s.id === id);
    if (!status) return { name: '未知', color: 'default' };
    
    const colors = {
      draft: 'blue',
      published: 'green',
      out_of_stock: 'orange',
      discontinued: 'red'
    };
    
    return { name: status.name, color: colors[id] || 'default' };
  };

  const handleSearch = (e) => {
    setSearchText(e.target.value);
  };

  const handleStatusChange = (id, checked) => {
    const newStatus = checked ? 'published' : 'draft';
    // 这里实际应调用API更新状态
    message.success(`商品状态已更新为${checked ? '上架' : '下架'}`);
    console.log(`更新商品 ${id} 状态为 ${newStatus}`);
  };

  const handleDelete = (id) => {
    // 这里实际应调用API删除商品
    message.success('商品已删除');
    console.log(`删除商品 ${id}`);
    onRefresh();
  };

  const filteredData = data.filter(item => {
    const matchesSearch = item.name.toLowerCase().includes(searchText.toLowerCase());
    const matchesStatus = selectedStatus ? item.status === selectedStatus : true;
    const matchesCategory = selectedCategory ? item.category === selectedCategory : true;
    return matchesSearch && matchesStatus && matchesCategory;
  });

  const columns = [
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      fixed: 'left',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      render: (categoryId) => (
        <Tag color="geekblue">{getCategoryName(categoryId)}</Tag>
      ),
      filters: productCategories.map(cat => ({
        text: cat.name,
        value: cat.id,
      })),
      onFilter: (value, record) => record.category === value,
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      render: (price) => `¥${price.toFixed(2)}`,
      sorter: (a, b) => a.price - b.price,
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      sorter: (a, b) => a.stock - b.stock,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (statusId, record) => {
        const statusInfo = getStatusInfo(statusId);
        return (
          <div className="status-cell">
            <Tag color={statusInfo.color}>{statusInfo.name}</Tag>
            {statusId === 'draft' || statusId === 'discontinued' ? (
              <Switch 
                size="small" 
                checked={statusId === 'published'} 
                onChange={(checked) => handleStatusChange(record.id, checked)}
                className="status-switch"
              />
            ) : null}
          </div>
        );
      },
      filters: productStatuses.map(s => ({
        text: s.name,
        value: s.id,
      })),
      onFilter: (value, record) => record.status === value,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date) => new Date(date).toLocaleDateString(),
      sorter: (a, b) => new Date(a.createdAt) - new Date(b.createdAt),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 120,
      render: (_, record) => (
        <Space>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => onEdit(record)}
          />
          <Popconfirm
            title="确定删除此商品？"
            onConfirm={() => handleDelete(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <Button 
              type="link" 
              danger 
              icon={<DeleteOutlined />} 
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className="product-table-container">
      <div className="table-toolbar">
        <div className="search-filter">
          <Input
            placeholder="搜索商品名称"
            prefix={<SearchOutlined />}
            style={{ width: 250 }}
            value={searchText}
            onChange={handleSearch}
            allowClear
          />
          
          <div className="quick-filters">
            <span>快速筛选:</span>
            <Button 
              type={!selectedStatus ? 'primary' : 'default'}
              onClick={() => setSelectedStatus(null)}
            >
              全部
            </Button>
            {productStatuses.map(status => (
              <Button 
                key={status.id}
                type={selectedStatus === status.id ? 'primary' : 'default'}
                onClick={() => setSelectedStatus(status.id)}
              >
                {status.name}
              </Button>
            ))}
          </div>
        </div>
        
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          onClick={onCreate}
        >
          添加商品
        </Button>
      </div>
      
      <Table 
        columns={columns} 
        dataSource={filteredData} 
        rowKey="id"
        scroll={{ x: 1200 }}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50'],
          showTotal: total => `共 ${total} 件商品`,
        }}
      />
    </div>
  );
};

export default ProductTable;